<template>
  <div class="student-extra-list">
    <a-card title="学生附加分管理">
      <a-form layout="inline" class="search-form">
        <a-form-item label="搜索">
          <a-input 
            v-model:value="searchForm.search" 
            placeholder="学号/姓名/用户名" 
            style="width: 200px" 
            allow-clear 
          />
        </a-form-item>
        <a-form-item label="班级">
          <a-input 
            v-model:value="searchForm.class_name" 
            placeholder="请输入班级" 
            style="width: 150px" 
            allow-clear 
          />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">查询</a-button>
            <a-button @click="handleReset">重置</a-button>
          </a-space>
        </a-form-item>
      </a-form>

      <a-table 
        :columns="columns" 
        :data-source="dataSource" 
        :loading="loading"
        bordered 
        :pagination="pagination"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'extra_count'">
            <a-tag color="blue" v-if="record.extra_count > 0">
              {{ record.extra_count }} 条
            </a-tag>
            <span v-else>0 条</span>
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a @click="handleViewStudent(record)">查看附加分</a>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 学生附加分详情弹窗 -->
    <a-modal
      v-model:open="detailModalVisible"
      :title="`${currentStudent?.username || ''} 的附加分记录`"
      width="1200px"
      :footer="null"
    >
      <div style="margin-bottom: 16px">
        <a-space>
          <a-button 
            type="primary" 
            @click="handleDownloadAll" 
            :loading="downloading"
            :disabled="studentExtraList.length === 0"
          >
            <template #icon><download-outlined /></template>
            下载全部证书（压缩包）
          </a-button>
          <a-tag color="blue">{{ studentExtraList.length }} 条记录</a-tag>
        </a-space>
      </div>
      
      <a-spin :spinning="detailLoading">
        <a-table 
          :columns="detailColumns" 
          :data-source="studentExtraList" 
          :pagination="false"
          bordered
          size="small"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'status'">
              <a-tag v-if="record.status === 'approved'" color="green">已通过</a-tag>
              <a-tag v-else-if="record.status === 'pending'" color="orange">待审核</a-tag>
              <a-tag v-else color="red">已拒绝</a-tag>
            </template>
            <template v-if="column.key === 'picture'">
              <a-image :src="record.picture_url || record.picture" :width="50" v-if="record.picture_url || record.picture" />
              <span v-else>-</span>
            </template>
            <template v-if="column.key === 'action'">
              <a-space>
                <a @click="handleViewDetail(record)">查看详情</a>
                <a @click="handleDownloadSingle(record)" v-if="record.picture_url || record.picture">
                  <download-outlined /> 下载证书
                </a>
              </a-space>
            </template>
          </template>
        </a-table>

        <div v-if="studentExtraList.length === 0" style="text-align: center; padding: 40px; color: #999;">
          暂无附加分记录
        </div>
      </a-spin>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { DownloadOutlined } from '@ant-design/icons-vue'
import { userAPI, type UserDetail } from '@/api/user'
import { extraReviewAPI, type ExtraReview } from '@/api/extraReview'
import { downloadFromServer } from '@/utils/cosUpload'
import JSZip from 'jszip'
import { saveAs } from 'file-saver'

const router = useRouter()
const loading = ref(false)
const dataSource = ref<any[]>([])
const detailModalVisible = ref(false)
const detailLoading = ref(false)
const downloading = ref(false)
const currentStudent = ref<UserDetail | null>(null)
const studentExtraList = ref<ExtraReview[]>([])

const searchForm = reactive({
  search: '',
  class_name: ''
})

const columns = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 80 },
  { title: '用户名', dataIndex: 'username', key: 'username', width: 120 },
  { title: '姓名', key: 'name', width: 100, customRender: ({ record }: any) => {
    return `${record.last_name || ''}${record.first_name || ''}` || '-'
  }},
  { title: '学号', dataIndex: ['profile', 'student_id'], key: 'student_id', width: 120 },
  { title: '班级', dataIndex: ['profile', 'class_name'], key: 'class_name', width: 120 },
  { title: '专业', dataIndex: ['profile', 'major'], key: 'major', width: 150 },
  { title: '附加分记录数', key: 'extra_count', width: 120 },
  { title: '操作', key: 'action', width: 120, fixed: 'right' }
]

const detailColumns = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 60 },
  { title: '证书名称', dataIndex: 'name', key: 'name', width: 150 },
  { title: '级别', dataIndex: 'ranks', key: 'ranks', width: 100 },
  { title: '等级', dataIndex: 'levels', key: 'levels', width: 100 },
  { title: '分数', dataIndex: 'grade', key: 'grade', width: 80 },
  { title: '证书图片', key: 'picture', width: 80 },
  { title: '审核状态', key: 'status', width: 100 },
  { title: '提交时间', dataIndex: 'submit_at', key: 'submit_at', width: 150 },
  { title: '操作', key: 'action', width: 100 }
]

const pagination = ref({
  total: 0,
  current: 1,
  pageSize: 30,
  showSizeChanger: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination.value.current = page
    pagination.value.pageSize = pageSize
    loadData()
  }
})

// 加载学生列表数据
const loadData = async () => {
  loading.value = true
  try {
    const res = await userAPI.getUserList({
      page: pagination.value.current,
      page_size: pagination.value.pageSize,
      search: searchForm.search || undefined,
      class_name: searchForm.class_name || undefined
    })
    
    // 为每个学生获取附加分数量
    const studentsWithCount = await Promise.all(
      res.data.results.map(async (student) => {
        try {
          const extraRes = await extraReviewAPI.getExtraReviewList({
            student: student.id,
            page_size: 1
          })
          return {
            ...student,
            extra_count: extraRes.data.count || 0
          }
        } catch {
          return {
            ...student,
            extra_count: 0
          }
        }
      })
    )
    
    dataSource.value = studentsWithCount
    pagination.value.total = res.data.count
  } catch (error: any) {
    message.error('加载数据失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.value.current = 1
  loadData()
}

// 重置
const handleReset = () => {
  searchForm.search = ''
  searchForm.class_name = ''
  pagination.value.current = 1
  loadData()
}

// 查看学生的附加分记录
const handleViewStudent = async (student: UserDetail) => {
  currentStudent.value = student
  detailModalVisible.value = true
  detailLoading.value = true
  
  try {
    const res = await extraReviewAPI.getExtraReviewList({
      student: student.id,
      page_size: 100
    })
    studentExtraList.value = res.data.results
  } catch (error: any) {
    message.error('加载附加分记录失败: ' + (error.response?.data?.message || error.message))
  } finally {
    detailLoading.value = false
  }
}

// 查看附加分详情
const handleViewDetail = (record: ExtraReview) => {
  router.push(`/extra-review/detail/${record.id}`)
  detailModalVisible.value = false
}

// 下载单个证书
const handleDownloadSingle = async (record: ExtraReview) => {
  const imageUrl = record.picture_url || record.picture
  if (!imageUrl) {
    message.warning('该记录没有证书图片')
    return
  }
  
  try {
    // 使用统一的下载工具
    const result = await downloadFromServer(imageUrl)
    
    if (!result.success || !result.blob) {
      throw new Error(result.message)
    }
    
    const fileName = sanitizeFileName(`${record.name}_${record.ranks}_${record.levels}.${getFileExtension(imageUrl)}`)
    saveAs(result.blob, fileName)
    message.success('下载成功')
  } catch (error) {
    message.error('下载失败: ' + (error as Error).message)
  }
}

// 下载全部证书（压缩包）
const handleDownloadAll = async () => {
  const recordsWithImages = studentExtraList.value.filter(r => r.picture_url || r.picture)
  
  if (recordsWithImages.length === 0) {
    message.warning('没有可下载的证书图片')
    return
  }
  
  downloading.value = true
  message.loading({ content: '正在打包下载...', key: 'download', duration: 0 })
  
  try {
    const zip = new JSZip()
    const folder = zip.folder(`${currentStudent.value?.username || 'student'}_certificates`)
    
    // 下载所有图片并添加到压缩包
    const downloadPromises = recordsWithImages.map(async (record, index) => {
      const imageUrl = record.picture_url || record.picture
      try {
        // 使用统一的下载工具
        const result = await downloadFromServer(imageUrl!)
        
        if (!result.success || !result.blob) {
          throw new Error(result.message)
        }
        
        const fileName = sanitizeFileName(`${index + 1}_${record.name}_${record.ranks}_${record.levels}.${getFileExtension(imageUrl!)}`)
        folder?.file(fileName, result.blob)
      } catch (error) {
        console.error(`下载失败: ${record.name}`, error)
      }
    })
    
    await Promise.all(downloadPromises)
    
    // 生成压缩包并下载
    const content = await zip.generateAsync({ type: 'blob' })
    const zipFileName = `${currentStudent.value?.username || 'student'}_证书_${new Date().getTime()}.zip`
    saveAs(content, zipFileName)
    
    message.success({ content: `成功下载 ${recordsWithImages.length} 个证书`, key: 'download' })
  } catch (error) {
    message.error({ content: '打包下载失败: ' + (error as Error).message, key: 'download' })
  } finally {
    downloading.value = false
  }
}

// 清理文件名，移除特殊字符
const sanitizeFileName = (name: string): string => {
  return name
    .replace(/[\\/:*?"<>|]/g, '_')  // 替换不允许的字符
    .replace(/\s+/g, '_')  // 替换空格
    .replace(/\_+/g, '_')  // 合并多个下划线
    .trim()
}

// 获取文件扩展名
const getFileExtension = (url: string): string => {
  // 先解码URL，然后提取扩展名
  try {
    const decodedUrl = decodeURIComponent(url)
    const match = decodedUrl.match(/\.([a-zA-Z0-9]+)(\?|$)/)
    return match && match[1] ? match[1].toLowerCase() : 'png'
  } catch {
    // 如果解码失败，尝试直接匹配
    const match = url.match(/\.([a-zA-Z0-9]+)(\?|$)/)
    return match && match[1] ? match[1].toLowerCase() : 'png'
  }
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.search-form {
  margin-bottom: 20px;
}
</style>
